package vnc.server.rfb.messages;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.net.Socket;


public class PointerEventMessage extends Message {
	
	private final Robot robot;
	private int currentKey = 0;
	public PointerEventMessage(Socket clientSocket) throws AWTException
	{
		super(clientSocket, ProcessMode.read);
		this.robot = new Robot();
		currentKey = InputEvent.BUTTON1_MASK;
	}
	
	@Override
	public Object doReadMessage() throws IOException {
		//System.out.println(this.toString());

		byte buttonMask = din.readByte();
		short x = din.readShort();
		short y = din.readShort();
		
		if ( buttonMask == 0 ){
			// no button is pressed
			if ( currentKey != 0 ){// check previously pressed button 
				//send released/up event for this button
				sendMouseEvent(x, y, currentKey, false);
				currentKey = 0;
			} else {
				// no previous button pressed/down. just move.
				moveMouse(x, y);
			}
		} else {
			// a mouse button is pressed.
			// store this code
			currentKey = convertToAwtMouseBtnCode(buttonMask);
			// send press event
			sendMouseEvent(x, y, currentKey, true);
		}
		return null;
	}
	
	private int convertToAwtMouseBtnCode(byte mask){
		int code = 0;
		if ( (mask & 1) > 0  )
			code |= InputEvent.BUTTON1_MASK;
		if ( (mask & (1<<1)) > 0  )
			code |= InputEvent.BUTTON2_MASK;
		if ( (mask & (1<<2)) > 0  )
			code |= InputEvent.BUTTON3_MASK;
		return code;
	}
	/**
	 * 
	 * @param params 
	 */
	public void moveMouse(int x, int y) {
	    if (x >= 0 && y >= 0) {
	        robot.mouseMove(x, y);
	    }
	}
	
	public void sendMouseEvent(int x, int y, int btnCode, boolean isPress) {
		if (x >= 0 && y >= 0) {
			robot.mouseMove(x, y);
			if (isPress){
				robot.mousePress(btnCode);
			} else {
				robot.mouseRelease(btnCode);
			}
			try {
				//Thread.sleep(100);
				//Main.update.process();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
